package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.common.CommonResult;
import com.easy.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在处理handler之前执行
        // 返回true就可以执行handler，返回false执行不到
        //return true/false是Spring MVC 中运行路线需求，不是回应给浏览器的结果

        //验证每个请求是否是登录状态
        //怎样就是登录状态  有token，token有效  有登录状态
        //token在哪？ 在header中   叫做Authorization
        String token  = request.getHeader("Authorization");
        if(token!=null && JWTUtil.verifyToken(token)){
            //有token，token有效  有登录状态
            return true;
        }else {
            //要回应的数据
            CommonResult result=CommonResult.fail(400,"未登录");
            //将数据解析成JSON
            String json= JSON.toJSONString(result);
            //将数据回应
            response.getWriter().write(json);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
